//
//  ZCHomeViewController.m
//  kangbs
//
//  Created by 高睿婕 on 2018/8/14.
//  Copyright © 2018年 Regina. All rights reserved.
//

#import "ZCHomeViewController.h"
#import "ZCHomeView.h"
#import "ZCUserInfoModel.h"
#import "ZCTakeCarViewController.h"
#import "ZCTakeCarSearchViewController.h"
#import "ZCAbnormalViewController.h"
#import "UWRQViewController.h"
#import "ZCTakeCarDetailViewController.h"
#import "ZCTaskModel.h"
#import "ZCAssignCodeViewController.h"
#import "ZCQualityTestingViewController.h"
#import "ZCStorageAllocationViewController.h"
#import "ZCPutInStorageViewController.h"
#import "ZCPreparationViewController.h"
#import "ZCOutboundCommitViewController.h"
#import "ZCOutboundPlanViewController.h"
#import "ZCAdjustmentViewController.h"
#import "ZCLoadingViewController.h"
#import "ZCShipmentViewController.h"
#import "ZCTakeCarSearchViewController.h"
#import "ZCCancellingStocksViewController.h"


@interface ZCHomeViewController ()<ZCHomeViewDelegate, uwRQDelegate>

@property (nonatomic, strong) ZCHomeView *homeView;
@property (nonatomic, strong) ZCUserInfoModel *userInfoModel;
@property (nonatomic, strong) ZCAppVersionModel *versionModel;
@property (nonatomic, strong) MBProgressHUD *hud;

@end

@implementation ZCHomeViewController
#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"康舶司";
    self.homeView = [[ZCHomeView alloc] initWithFrame:self.view.bounds];
    self.homeView.delegate = self;
    [self.view addSubview:self.homeView];
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hud];
    [self loadData];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
    [self.hud hideAnimated:YES];
    self.hud.mode = MBProgressHUDModeIndeterminate;
    self.hud.label.text = nil;
}

#pragma mark - 网络请求
- (void)loadData {
    __weak typeof(self)weakSelf = self;
    [self.hud showAnimated:YES];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool updateBaseURL:hostURL];
        NSLog(@"url:%@",[NSString stringWithFormat:@"%@%@",hostURL,UserInfo]);
        [ZCHttpTool getWithURL:UserInfo params:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue] == 0) {
                [weakSelf.hud hideAnimated:YES];
                NSDictionary *dataDic = responseObject[@"data"];
                weakSelf.userInfoModel = [[ZCUserInfoModel alloc] init];
                weakSelf.userInfoModel = [ZCUserInfoModel yy_modelWithDictionary:dataDic];
                //保存用户信息
                [[NSUserDefaults standardUserDefaults] setObject:weakSelf.userInfoModel.code forKey:UserCode];
                [[NSUserDefaults standardUserDefaults] setObject:weakSelf.userInfoModel.name forKey:UserName];
                [[NSUserDefaults standardUserDefaults] setObject:weakSelf.userInfoModel.mobile forKey:UserMobile];
                [[NSUserDefaults standardUserDefaults] setObject:weakSelf.userInfoModel.email forKey:UserEmail];
                ZCUserInfoStoreModel *storeM = [weakSelf.userInfoModel.storehouses firstObject];
                [[NSUserDefaults standardUserDefaults] setObject:storeM.storeId forKey:UserStoreId];
                [[NSUserDefaults standardUserDefaults] setObject:storeM.name forKey:UserStoreName];
                [[NSUserDefaults standardUserDefaults] synchronize];
                dispatch_async(dispatch_get_main_queue(), ^{
                    weakSelf.homeView.permissionArr = weakSelf.userInfoModel.permissions;
                });
                [weakSelf versionChange];
            }else {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
            
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
}


//版本更新
- (void)versionChange {
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool getWithURL:AppVersion params:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"success"] boolValue]) {
                weakSelf.versionModel = [ZCAppVersionModel yy_modelWithDictionary:responseObject[@"data"]];
                NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
                NSString *currentVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];
                if ([weakSelf.versionModel.version compare:currentVersion options:NSNumericSearch] == NSOrderedDescending) {
                    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:weakSelf.versionModel.releaseNote message:weakSelf.versionModel.releaseNoteCN preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *updateAction = [UIAlertAction actionWithTitle:@"立即更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:weakSelf.versionModel.url]];
                    }];
                    
                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                    [alertVC addAction:updateAction];
                    if ([weakSelf.versionModel.isForce integerValue] == 0) {
                        [alertVC addAction:cancelAction];
                    }
                    [weakSelf presentViewController:alertVC animated:YES completion:nil];
                }
            }
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            
        }];
    });
}

#pragma mark - ZCHomeViewDelegate
- (void)ZCHomeViewCollectionViewCellWithIndex:(NSInteger)index {
    ZCUserInfoPermissionModel *permissionModel = (ZCUserInfoPermissionModel *)self.userInfoModel.permissions[index];
    
    if ([permissionModel.name isEqualToString:@"提车任务"]) {
        ZCTakeCarViewController *taskCarVC = [[ZCTakeCarViewController alloc] init];
        [self.navigationController pushViewController:taskCarVC animated:YES];
        
    }else if ([permissionModel.name isEqualToString:@"异常登记"]) {
        ZCAbnormalViewController *abnormalVC = [[ZCAbnormalViewController alloc] init];
        [self.navigationController pushViewController:abnormalVC animated:YES];
        
    }else if ([permissionModel.name isEqualToString:@"快速赋码"]) {
        ZCAssignCodeViewController *assignCodeVC = [[ZCAssignCodeViewController alloc] init];
        [self.navigationController pushViewController:assignCodeVC animated:YES];
        
    }else if ([permissionModel.name isEqualToString:@"入库计划"]) {
        ZCPutInStorageViewController *putInStorageVC = [[ZCPutInStorageViewController alloc] init];
        [self.navigationController pushViewController:putInStorageVC animated:YES];
        
    }else if ([permissionModel.name isEqualToString:@"收车质检"]) {
        ZCQualityTestingViewController *qualityTestingVC = [[ZCQualityTestingViewController alloc] init];
        [self.navigationController pushViewController:qualityTestingVC animated:YES];
        
    }else if ([permissionModel.name isEqualToString:@"分配入库"]) {
        ZCStorageAllocationViewController *allocationVC = [[ZCStorageAllocationViewController alloc] init];
        [self.navigationController pushViewController:allocationVC animated:YES];
        
    }else if ([permissionModel.name isEqualToString:@"出库计划"]) {
        ZCOutboundPlanViewController *obPlanVC = [[ZCOutboundPlanViewController alloc] init];
        [self.navigationController pushViewController:obPlanVC animated:YES];
        
    }else if ([permissionModel.name isEqualToString:@"备料任务"]) {
        ZCPreparationViewController *preparationVC = [[ZCPreparationViewController alloc] init];
        [self.navigationController pushViewController:preparationVC animated:YES];
    }else if ([permissionModel.name isEqualToString:@"出库确认"]) {
        ZCOutboundCommitViewController *obCommitVC = [[ZCOutboundCommitViewController alloc] init];
        [self.navigationController pushViewController:obCommitVC animated:YES];
        
    }else if ([permissionModel.name isEqualToString:@"库位调整"]) {
        ZCAdjustmentViewController *adjustmentVC = [[ZCAdjustmentViewController alloc] init];
        [self.navigationController pushViewController:adjustmentVC animated:YES];
        
    }else if ([permissionModel.name isEqualToString:@"装车交验"]) {
        ZCLoadingViewController *loadingVC = [[ZCLoadingViewController alloc] init];
        [self.navigationController pushViewController:loadingVC animated:YES];
        
    }else if ([permissionModel.name isEqualToString:@"确认发运"]) {
        ZCShipmentViewController *shipmentVC = [[ZCShipmentViewController alloc] init];
        [self.navigationController pushViewController:shipmentVC animated:YES];
    }else if ([permissionModel.name isEqualToString:@"退库任务"]) {
        ZCCancellingStocksViewController *cancellingVC = [[ZCCancellingStocksViewController alloc] init];
        [self.navigationController pushViewController:cancellingVC animated:YES];
    }
}

- (void)ZCHomeViewSearchButtonClick {
    ZCTakeCarSearchViewController *searchTakeCarVC = [[ZCTakeCarSearchViewController alloc] init];
    [self.navigationController pushViewController:searchTakeCarVC animated:YES];
}

- (void)ZCHomeViewQRCodeButtonClick {
    UWRQViewController *qrCodeVC = [[UWRQViewController alloc] init];
    qrCodeVC.alertTitle = @"请扫描车的二维码";
    qrCodeVC.delegate = self;
    qrCodeVC.fromAuthierVC = NO;
    [self.navigationController pushViewController:qrCodeVC animated:YES];
}

#pragma mark - uwRQDelegate
- (void)uwRQFinshedScan:(NSString *)result {
    NSArray *arr = [result componentsSeparatedByString:@","];
    NSString *keyId = [arr firstObject];
    ZCTakeCarSearchViewController *searchVC = [[ZCTakeCarSearchViewController alloc] init];
    searchVC.queryParam = keyId;
    [self.navigationController pushViewController:searchVC animated:YES];
//    NSMutableDictionary *param = [NSMutableDictionary dictionary];
//    [param setObject:keyId forKey:@"queryParam"];
//    __weak typeof(self)weakSelf = self;
//    dispatch_async(dispatch_get_global_queue(0, 0), ^{
//        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];
//        [SVProgressHUD show];
//        [ZCHttpTool postWithURL:SearchByQRCode params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            if ([responseObject[@"success"] boolValue]) {
//                [SVProgressHUD showSuccessWithStatus:@"查询成功"];
//                ZCTaskDetailModel *taskDetail = [ZCTaskDetailModel yy_modelWithDictionary:responseObject[@"data"]];
//                ZCTakeCarDetailViewController *detailVC = [[ZCTakeCarDetailViewController alloc] init];
//                detailVC.taskId = taskDetail.taskId;
//                detailVC.taskType = taskDetail.taskType;
//                detailVC.fromSearch = YES;
//                [weakSelf.navigationController pushViewController:detailVC animated:YES];
//            }else {
//                [SVProgressHUD showErrorWithStatus:responseObject[@"message"]];
//            }
//
//        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
//            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
//        }];
//    });
}


@end
